<template>
  <div style="min-height: 300px">
    <el-form ref="stuForm" :model="entity" :rules="rules" label-width="120px">
      <el-form-item label="姓名" prop="name">
        <el-input v-model="entity.name" placeholder="姓名" ref="name" />
      </el-form-item>
      <el-form-item label="年龄" prop="age">
        <el-input v-model.number="entity.age" placeholder="年龄" />
      </el-form-item>
      <el-form-item label="出生日期" prop="birth">
        <el-date-picker v-model="entity.birth" type="date" placeholder="出生日期" style="width: 100%;" value-format="yyyy-MM-dd" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="btnSubmit" size="default">确 定</el-button>
        <el-button @click="onCancel" size="default">取 消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup name="studentDetail">
import request from '/@/utils/request';
import dayjs from "dayjs";
import { ElMessage } from 'element-plus';
import mittBus from '/@/utils/mitt';
import {reactive, ref, onMounted, defineProps, defineEmits, nextTick} from "vue";

const stuForm = ref(null)
const name = ref(null)
const emit = defineEmits(['update:modelValue'])
let props = defineProps({
  modelValue : {type : Boolean, default: true},
  entityId : {type : Number, default: 0}
})

let entity = ref({
  id : props.entityId,
  name: '',
  age: '',
  birth: '',
})
const rules = reactive({
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  age: [
    { required: true, message: '请输入年龄', trigger: 'blur' }
  ],
  birth: [
    { required: true, message: '请输入出生日期', trigger: 'blur' }
  ]
})

const loadEntity = ()=>{
  if(props.entityId > 0){
    request({ url: '/student/getstudent', data: {id : props.entityId} }).then( res =>{
      entity.value = res.data
      entity.value.birth= dayjs(entity.value.birth).format('YYYY-MM-DD')
    })
  }
}
const btnSubmit = ()=>{
  if(!stuForm.value) return;
  stuForm.value.validate((valid)=>{
    if(valid){
      request({
        url: '/student/addeditstudent',
        data: entity.value
      }).then( res =>{
        if(res.code === "200"){
          ElMessage.success(res.msg)
          emit('update:modelValue', false) //关闭弹窗
          props.entityId > 0 ? mittBus.emit('stuedit', {}) : mittBus.emit('stuadd', {}); //触发事件总线，让列表界面更新数据
        }else{
          ElMessage.error(res.msg);
        }
      })
    }else{
      console.log('error submit!!');
      return false;
    }
  })
}
const onCancel = ()=>{
  emit('update:modelValue', false) //关闭弹窗
}

onMounted(()=>{
  loadEntity()
  nextTick(()=>{
    name.value.focus();
  })
})
</script>
<style scoped>
</style>
